#include <stdio.h>
#include <stdlib.h>
#include <poll.h>
#include <unistd.h>

int main()
{
    struct pollfd fds[1];      // 文件描述符数组
    fds[0].fd = STDIN_FILENO;  // 标准输入
    fds[0].events = POLLIN;    // 监听可读事件
    // fds[1].fd = STDOUT_FILENO; // 标准输出
    // fds[1].events = POLLOUT;   // 监听可写事件

    int timeout = 5000; // 5 秒超时

    printf("Waiting for input or output readiness...\n");

    int ready = poll(fds, 1, timeout);

    if (ready == -1)
    {
        perror("poll");
        return 1;
    }
    else if (ready == 0)
    {
        printf("Timeout! No events.\n");
    }
    else
    {
        if (fds[0].revents & POLLIN)
        {
            char buffer[256];
            if (fgets(buffer, sizeof(buffer), stdin) != NULL)
            {
                printf("You typed: %s", buffer);
            }
        }
    }

    return 0;
}